package com.test.jdbc.dao.impl;

import com.test.jdbc.dao.AccountDao;
import com.test.jdbc.entity.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.util.List;

/**
 * @Author zz-lxf
 * @E-mail 629938044@qq.com
 * @Date 2021/12/4 15:53
 * @Version 1.0
 */
public class AccountDaoImpl implements AccountDao {

    // 声明一个JdbcTmplate属性及其Setter方法
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public int addAccount(Account account) {
        // 定义SQL
        String sql = "insert into account(username,balance) value(?,?)";
        // 定义数组来存放SQL语句中的参数
        Object[] obj = new Object[]{account.getUsername(), account.getBalance(),};
        // 执行添加操作，返回受SQL语句影响的条数
        int num = this.jdbcTemplate.update(sql, obj);
        return num;
    }

    @Override
    public int updateAccount(Account account) {
        // 定义SQL
        String sql = "update account set username=? , balance=? where id=?";
        // 定义数组来存放SQL语句中的参数
        Object[] obj = new Object[]{account.getUsername(), account.getBalance(), account.getId()};
        // 执行更新操作，返回受SQL语句影响的条数
        int num = this.jdbcTemplate.update(sql, obj);
        return num;
    }

    @Override
    public int deleteAccount(int id) {
        // 定义SQL
        String sql = "delete from account where id=?";
        // 执行更新操作，返回受SQL语句影响的条数
        int num = this.jdbcTemplate.update(sql, id);
        return num;
    }

    @Override
    public Account findAccountById(int id) {
        String sql = "select id,username,balance from account where id = ?";
        RowMapper<Account> rowMapper = new BeanPropertyRowMapper<Account>(Account.class);
        return this.jdbcTemplate.queryForObject(sql, rowMapper, id);
    }

    @Override
    public List<Account> findAllAccount() {
        String sql = "select id,username,balance from account";
        RowMapper<Account> rowMapper = new BeanPropertyRowMapper<Account>(Account.class);
        return this.jdbcTemplate.query(sql, rowMapper);
    }
}
